package com.dc.kylin.timedscheduling.config;

import com.dc.kylin.timedscheduling.service.ScheduledTaskExecutor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.Instant;
import java.util.Date;

@Data
@Configuration
@EnableScheduling
public class ScheduleTaskConfig implements SchedulingConfigurer {

    @Autowired
    private ScheduledTaskExecutor scheduledTaskExecutor;

    private String cronExpression = "0/5 * * * * ?"; // 默认每 5 秒执行一次

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> scheduledTaskExecutor.executeTask(), new Trigger() {
                    @Override
                    public Instant nextExecution(TriggerContext triggerContext) {
                        CronTrigger cronTrigger = new CronTrigger(cronExpression);
                        return cronTrigger.nextExecution(triggerContext);
                    }
                }
        );






    }

    // 提供一个方法用于动态修改定时任务的表达式
    public void setCronExpression(String expression) {
        cronExpression = expression;
    }
}
